using System;
using System.Diagnostics;
using Hydra.Shell.Interfaces;
using Hydra.Shell.Enumerations;
using Hydra.Shell.Constants;
using Hydra.Shell.Exceptions;
using Hydra.Shell;
using Hydra.Shell.DelayObjects;
using SLControlLibrary;

namespace Hydra.PackageFramework
{
	/// <summary>
	/// This class handles opening, saving of file items in the hierarchy.
	/// </summary>
	public class ObjectDocumentManager : DocumentManager
	{
		#region ctors

        private UIThread uiThread;

		public ObjectDocumentManager(UIThread uiThread, ObjectNode node) : base(node)
		{
            this.uiThread = uiThread;
		}
		#endregion

		#region overriden methods

		/// <summary>
		/// Open a file using the standard editor
		/// </summary>
		/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
		/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
		/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
		/// <param name="windowFrameAction">Determine the UI action on the document window</param>
		/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public override bool Open(ref Guid logicalView, IUnknown docDataExisting, out IHydraWindowFrame windowFrame, WindowFrameShowAction windowFrameAction)
		{
			bool newFile = false;
			bool openWith = false;
			return this.Open(newFile, openWith, ref logicalView, docDataExisting, out windowFrame, windowFrameAction);
		}

		/// <summary>
		/// Open a file with a specific editor
		/// </summary>
		/// <param name="editorFlags">Specifies actions to take when opening a specific editor. Possible editor flags are defined in the enumeration Microsoft.VisualStudio.Shell.Interop.__VSOSPEFLAGS</param>
		/// <param name="editorType">Unique identifier of the editor type</param>
		/// <param name="physicalView">Name of the physical view. If null, the environment calls MapLogicalView on the editor factory to determine the physical view that corresponds to the logical view. In this case, null does not specify the primary view, but rather indicates that you do not know which view corresponds to the logical view</param>
		/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
		/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
		/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
		/// <param name="windowFrameAction">Determine the UI action on the document window</param>
		/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public override bool OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IUnknown docDataExisting, out IHydraWindowFrame windowFrame, WindowFrameShowAction windowFrameAction)
		{
			windowFrame = null;
			bool newFile = false;
			bool openWith = false;
			return this.Open(newFile, openWith, editorFlags, ref editorType, physicalView, ref logicalView, docDataExisting, out windowFrame, windowFrameAction);
		}

		#endregion

		#region public methods
		/// <summary>
		/// Open a file in a document window with a std editor
		/// </summary>
		/// <param name="newFile">Open the file as a new file</param>
		/// <param name="openWith">Use a dialog box to determine which editor to use</param>
		/// <param name="windowFrameAction">Determine the UI action on the document window</param>
		/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
		public int Open(bool newFile, bool openWith, WindowFrameShowAction windowFrameAction)
		{
			Guid logicalView = Guid.Empty;
			IHydraWindowFrame windowFrame = null;
			return this.Open(newFile, openWith, logicalView, out windowFrame, windowFrameAction);
		}

		/// <summary>
		/// Open a file in a document window with a std editor
		/// </summary>
		/// <param name="newFile">Open the file as a new file</param>
		/// <param name="openWith">Use a dialog box to determine which editor to use</param>
		/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
		/// <param name="frame">A reference to the window frame that is mapped to the file</param>
		/// <param name="windowFrameAction">Determine the UI action on the document window</param>
		/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
		public int Open(bool newFile, bool openWith, Guid logicalView, out IHydraWindowFrame frame, WindowFrameShowAction windowFrameAction)
		{
			frame = null;
            IHydraRunningDocumentTable rdt = null;
            int returnValue = HydraConstants.S_OK;
            var serviceName = "IHydraRunningDocumentTable";

            var delayedWindowFrame = new DelayedWindowFrame(this.Log, TimeSpan.FromSeconds(40));

            frame = delayedWindowFrame;

            Func<IHydraRunningDocumentTable, int> continueOpen = (t) =>
            {
                Debug.Assert(t != null, " Could not get runnin1002-document table from the services exposed by this project");

                delayedWindowFrame.SetStatus("Opening...", 20, 100);

                if (t == null)
                {
                    return HydraConstants.E_FAIL;
                }

                // First we see if someone else has opened the requested view of the file.
                HydraRunningDocumentTableFlags flags = HydraRunningDocumentTableFlags.NoLock;
                uint itemid;
                IUnknown docData;
                IHydraHierarchy ivsHierarchy;
                uint docCookie;
                string path = this.GetFullPathForDocument();
                IHydraWindowFrame frame2;

                try
                {
                    delayedWindowFrame.ReportHistory("Searching {0} for document named '{1}': ", serviceName,  path);

                    rdt.FindAndLockDocument(flags, path, out ivsHierarchy, out itemid, out docData, out docCookie);

                    delayedWindowFrame.ReportHistory(ReportHistoryType.OpeningFile, path);

                    this.Open(newFile, openWith, ref logicalView, docData, out frame2, windowFrameAction);

                    if (frame2 is DelayedWindowFrame)
                    {
                        delayedWindowFrame.Wrap(((DelayedWindowFrame)frame2));
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Exception :" + e.Message);
                    returnValue = HydraConstants.E_FAIL;
                }

                return returnValue;
            };

            Func<Hydra.Shell.Interfaces.IServiceProvider, int> getServiceAndOpen = (s) =>
            {
                try
                {
                    rdt = s.GetService<IHydraRunningDocumentTable>();

                    return continueOpen(rdt);
                }
                catch (ServiceAvailableButNotLoadedException ex)
                {
                    ServiceLoadOperation<IHydraRunningDocumentTable> loadOp;

                    delayedWindowFrame.ReportHistory(ex);
                    delayedWindowFrame.ReportHistory(ReportHistoryType.QueryingForServiceWithTimeout, serviceName, TimeSpan.FromSeconds(20));

                    if (ex.QueryServiceProvider.QueryService<IHydraRunningDocumentTable>(typeof(IHydraRunningDocumentTable).GetGuid(), out loadOp))
                    {
                        delayedWindowFrame.ReportHistory(ReportHistoryType.QueryRequestReturned, serviceName, true);

                        loadOp.ExceptionOccured += (sender, e) =>
                        {
                            delayedWindowFrame.ReportHistory(e.Exception);

                            Debugger.Break();
                        };

                        loadOp.ServiceLoaded += (sender, e) =>
                        {
                            rdt = loadOp.Service;

                            delayedWindowFrame.ReportHistory(ReportHistoryType.ServiceLoadedSuccessfullyContinue, serviceName, "open");

                            returnValue = continueOpen(rdt);

                            Debug.Assert(returnValue == HydraConstants.S_OK);
                        };

                        return HydraConstants.E_PENDING;
                    }
                    else
                    {
                        return HydraConstants.E_FAIL;
                    }
                }
            };

            try
            {
                delayedWindowFrame.ReportHistory(ReportHistoryType.AttemptingToGetService, serviceName);

                var service = this.Node.ProjectMgr.Site;

                getServiceAndOpen(service);

                return HydraConstants.E_PENDING;
            }
            catch (ObjectNotYetSitedException ex)
            {
                ex.WatchForSited(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10));

                delayedWindowFrame.ReportHistory(ex, "Waiting for object to be sited");

                ex.OnException += (sender, e) =>
                {
                    delayedWindowFrame.SetException(e.Value);
                };

                ex.OnSited += (sender, e) =>
                {
                    getServiceAndOpen(e.Value);
                };

                return HydraConstants.E_PENDING;
            }
        }

		#endregion

		#region virtual methods
		/// <summary>
		/// Open a file in a document window
		/// </summary>
		/// <param name="newFile">Open the file as a new file</param>
		/// <param name="openWith">Use a dialog box to determine which editor to use</param>
		/// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param>
		/// <param name="docDataExisting">IntPtr to the IUnknown interface of the existing document data object</param>
		/// <param name="windowFrame">A reference to the window frame that is mapped to the file</param>
		/// <param name="windowFrameAction">Determine the UI action on the document window</param>
		/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
		public virtual bool Open(bool newFile, bool openWith, ref Guid logicalView, IUnknown docDataExisting, out IHydraWindowFrame windowFrame, WindowFrameShowAction windowFrameAction)
		{
			windowFrame = null;
			Guid editorType = Guid.Empty;
			return this.Open(newFile, openWith, 0, ref editorType, null, ref logicalView, docDataExisting, out windowFrame, windowFrameAction);
		}

		#endregion

		#region helper methods

		private bool Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IUnknown docDataExisting, out IHydraWindowFrame windowFrame, WindowFrameShowAction windowFrameAction)
		{
            var serviceName = "IHydraUIShellOpenDocument";

			windowFrame = null;

            if(this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed)
            {
                return false;
            }

			Debug.Assert(this.Node != null, "No node has been initialized for the document manager");
            //////Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager");
			Debug.Assert(this.Node is ObjectNode, "Node is not FileNode object");

			bool returnValue = false;
			string caption = this.GetOwnerCaption();
			string fullPath = this.GetFullPathForDocument();

            var editorType2 = editorType;
            var logicalView2 = logicalView;
            var delayedWindowFrame = new DelayedWindowFrame(this.Log, TimeSpan.FromSeconds(40));

            windowFrame = delayedWindowFrame;

            Func<IHydraUIShellOpenDocument, bool> continueOpen = (u) =>
            {
                var serviceProvider = this.Node.ProjectMgr.Site.GetService<IQueryServiceProvider>();
                IHydraWindowFrame windowFrame2 = delayedWindowFrame;

                try
                {
                    this.Node.ProjectMgr.OnOpenItem(fullPath);
                    bool result = false;

                    delayedWindowFrame.SetStatus("Opening " + fullPath, 40, 100);

                    if (openWith)
                    {
                        delayedWindowFrame.ReportHistory(ReportHistoryType.CallingFunction, "OpenStandardEditor");

                        result = u.OpenStandardEditor(HydraOpenStandardEditorFlags.UseOpenWithDialog, fullPath, ref logicalView2, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame2);
                    }
                    else
                    {
                        HydraOpenStandardEditorFlags openFlags = 0;
                        if (newFile)
                        {
                            openFlags |= HydraOpenStandardEditorFlags.OpenAsNewFile;
                        }

                        //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid
                        // of the node being opened, otherwise the debugger doesn't work.
                        if (editorType2 != Guid.Empty)
                        {
                            delayedWindowFrame.ReportHistory(ReportHistoryType.CallingFunction, "OpenSpecificEditor");

                            result = u.OpenSpecificEditor(editorFlags, fullPath, ref editorType2, physicalView, ref logicalView2, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame2);
                        }
                        else
                        {
                            delayedWindowFrame.ReportHistory(ReportHistoryType.CallingFunction, "OpenStandardEditor");

                            openFlags |= HydraOpenStandardEditorFlags.ChooseBestStdEditor;

                            result = u.OpenStandardEditor(openFlags, fullPath, ref logicalView2, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame2);

                            delayedWindowFrame.ReportHistory(ReportHistoryType.CallingFunctionReturnSuccessfully, "OpenStandardEditor");

                            if (windowFrame2 is DelayedWindowFrame)
                            {
                                delayedWindowFrame.Wrap((DelayedWindowFrame)windowFrame2);
                            }
                        }
                    }

                    if (windowFrame2 != null)
                    {
                        Func<IHydraWindowFrame, bool> showFrame = (f) =>
                        {
                            object var;

                            if (newFile)
                            {
                                windowFrame2.GetProperty(HydraFrameProperties.DocData, out var);
                                IHydraPersistDocData persistDocData = (IHydraPersistDocData)var;
                                persistDocData.SetUntitledDocPath(fullPath);
                            }

                            var = (int?) null;
                            windowFrame2.GetProperty(HydraFrameProperties.DocCookie, out var);
                            this.Node.DocCookie = (uint)int.Parse(var.ToString());

                            if (windowFrameAction == WindowFrameShowAction.Show)
                            {
                                windowFrame2.Show();
                            }
                            else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate)
                            {
                                windowFrame2.ShowNoActivate();
                            }
                            else if (windowFrameAction == WindowFrameShowAction.Hide)
                            {
                                windowFrame2.Hide();
                            }

                            return true;
                        };

                        if (windowFrame2 is DelayedWindowFrame)
                        {
                            delayedWindowFrame.Wrap(((DelayedWindowFrame)windowFrame2));

                            delayedWindowFrame.OnException += (sender, e) =>
                            {
                                Debugger.Break();
                            };

                            delayedWindowFrame.ObjectReady += (sender, e) =>
                            {
                                showFrame(e.RealObject);
                            };
                        }
                        else
                        {
                            showFrame(windowFrame2);
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Exception e:" + e.Message);
                    returnValue = false;
                    CloseWindowFrame(ref windowFrame2);
                }

                return true;
            };

            try
            {
                delayedWindowFrame.ReportHistory(ReportHistoryType.AttemptingToGetService, serviceName);

                var uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService<IHydraUIShellOpenDocument>();

                continueOpen(uiShellOpenDocument);
            }
            catch (ServiceAvailableButNotLoadedException ex)
            {
                ServiceLoadOperation<IHydraUIShellOpenDocument> loadOp;

                delayedWindowFrame.ReportHistory(ReportHistoryType.QueryingForService, serviceName);

                if (ex.QueryServiceProvider.QueryService<IHydraUIShellOpenDocument>(typeof(IHydraUIShellOpenDocument).GetGuid(), out loadOp))
                {
                    delayedWindowFrame.ReportHistory(ReportHistoryType.QueryRequestReturned, serviceName, true);

                    loadOp.ServiceLoaded += (sender, e) =>
                    {
                        delayedWindowFrame.ReportHistory(ReportHistoryType.ServiceLoadedSuccessfullyContinue, serviceName, "open");

                        continueOpen(loadOp.Service);
                    };

                    loadOp.ExceptionOccured += (sender, e) =>
                    {
                        delayedWindowFrame.SetException(e.Exception);
                    };
                }
            }
            catch (ServiceAvailableButRequiresDependenciesException ex)
            {
                var serviceLoadOperation = ex.Resolve<IHydraUIShellOpenDocument>(uiThread);

                serviceLoadOperation.ExceptionOccured += (sender, e) =>
                {
                    Debugger.Break();
                    throw e.Exception;
                };

                serviceLoadOperation.ServiceLoaded += (sender, e) =>
                {
                    var uiShellOpenDocument = (IHydraUIShellOpenDocument) e.Service;

                    continueOpen(uiShellOpenDocument);
                };
            }

			return returnValue;
		}

		#endregion
	}
}
